package com.edu.bean;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class MyIOC {
    Map<String, Object> map = new HashMap<>();

    public  MyIOC(String path) {
        Properties properties =new Properties();
        InputStream inputStream = MyIOC.class.getClassLoader().getResourceAsStream(path);
        try {
            if (inputStream == null)    {
                System.out.println("文件不存在！！！！！！！！");
                return;
            }
            properties.load(inputStream);
            Set<String> keys=properties.stringPropertyNames();
            for (String key : keys) {
              String className =  properties.getProperty(key);
              Class clazz=Class.forName(className);
                Constructor constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                Object object = constructor.newInstance();
                map.put(key,object);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public Object getBean(String beanId){
        return map.get(beanId);
    }

    public Object getBean(Class clazz){
        Set<String> keySet = map.keySet();
        for (String s : keySet) {
            if(map.get(s).getClass()==clazz){
                return map.get(s);
            }
        }
        return null;
    }
}
